package com.weixin.common.security.service;

import com.weixin.common.core.constant.CacheConstants;
import com.weixin.common.core.domain.LoginUser;
import com.weixin.common.core.form.LoginUserDetails;
import com.weixin.common.core.utils.TokenUtil;
import com.weixin.common.redis.service.RedisService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @version 1.0.0
 * @className: TokenService
 * @description:
 * @author: zhangjunfa
 * @date: 2023/6/19 16:24
 */
@Component
public class TokenService {
    private RedisService redisService;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private final static long expireTime = CacheConstants.EXPIRATION;

    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    private final static Long MILLIS_MINUTE_TEN = CacheConstants.REFRESH_TIME * MILLIS_MINUTE;

    public TokenService(RedisService redisService) {
        this.redisService = redisService;
    }

    public LoginUserDetails getLoginUser(String token) {
        String redisKey = TokenUtil.getRedisCacheKey(token);
        return this.redisService.getCacheObject(redisKey);
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUserDetails loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = TokenUtil.getRedisCacheKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 删除用户登录缓存
     *
     * @param redisCacheKey 删除redis缓存
     */
    public void delToken(String redisCacheKey) {
        this.redisService.deleteObject(redisCacheKey);
    }
}
